'''
Author: cw
Date: 2025-08-15
Description: ...
'''
from enum import Enum, auto
from sqlalchemy import select
from fapi import ServiceError

from utils import db_util
from models.mysql_model import ImageTask


class TaskStatus(Enum):
    RUNNING = auto()    #  制作中
    SUCCESSED = auto()  #  制作成功
    FAILED = auto()     #  制作失败
    # SENDED = auto()   #  发送用户完成
    # SEND_FAILED = auto()  #  发送用户失败

async def create(
    appid: str,
    openid: str,
    prompt: str,
    work_id: str
):
    """create"""
    question = ImageTask(
        appid=appid,
        openid=openid,
        prompt=prompt,
        work_id=work_id,
        status = TaskStatus.RUNNING.name
    )
    async with db_util.session_context() as session:
        return session.add(question)


async def get_latest_task(appid: str, openid: str) -> ImageTask:
    """get"""   
    async with db_util.session_context() as session:
        info = (await session.execute(
            select(ImageTask).filter(
                ImageTask.appid == appid,
                ImageTask.openid == openid,
            ).order_by(
                ImageTask.id.desc()
            )
        )).scalar()
        if not info:
            raise ServiceError('not find')
        return info.to_dict()


async def update_by_work_id(
    work_id: int,
    update_data: dict
) -> ImageTask:
    """update"""
    async with db_util.session_context() as session:
        result = (await session.execute(
            select(ImageTask).filter(
                ImageTask.work_id == work_id,
            )
        )).scalar()
        if not result:
            raise ServiceError('not find')
        for k, v in update_data.items():
            if hasattr(ImageTask, k) and v is not None:
                setattr(result, k, v)
        await session.flush()
        return result.to_dict()
